package com.ellricky.baselib.adapter.cla

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andr.common.ui.adapter.BaseRecyclerAdapter
import com.andr.common.ui.adapter.SmartViewHolder
import com.andr.common.util.EmptyUtil
import com.andr.common.util.ResUtil
import com.andr.common.util.ViewUtil
import com.ellricky.baselib.BaseConstant
import com.ellricky.baselib.R
import com.ellricky.baselib.adapter.CommonGridItemDecoration
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.entity.IdNameEntity
import com.ellricky.baselib.entity.new.ClassEntry
import com.ellricky.baselib.entity.new.StudentEntry
import com.ellricky.baselib.entity.new.TeacherEntry
import com.ellricky.baselib.listener.OnClassPersonListener
import com.ellricky.baselib.ui.cla.ClassManageFragment
import com.ellricky.baselib.util.GlideUtil
import com.flyco.roundview.RoundRelativeLayout
import com.flyco.roundview.RoundTextView
import de.hdodenhof.circleimageview.CircleImageView
import kotlin.reflect.typeOf

class ClassRoomAdapter(val act: Activity) :
    BaseRecyclerAdapter<IdNameEntity>(R.layout.base_adapter_class_room) {

    var curPos = 0

    override fun onBindViewHolder(vh: SmartViewHolder?, p1: IdNameEntity?, p2: Int) {
        vh?.let {
            it.text(R.id.tvClassRoom, p1?.name)

            val cvRoot = it.itemView.findViewById<CardView>(R.id.cvRoot)
            val tvClassRoom = it.itemView.findViewById<TextView>(R.id.tvClassRoom)

            tvClassRoom.text = p1?.name

            if (curPos == p2) {
                cvRoot.setCardBackgroundColor(Color.parseColor("#BE4938"))
                tvClassRoom.setTextColor(ResUtil.getColor(act, R.color.common_main_white))
            } else {
                cvRoot.setCardBackgroundColor(ResUtil.getColor(act, R.color.common_main_white))
                tvClassRoom.setTextColor(ResUtil.getColor(act, R.color.common_main_black))
            }
        }
    }

}


class ClassManageAdapter(
    private val activity: Activity,
    private val type: String,
    val listener: OnClassPersonListener?
) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    val dataSource: MutableList<ClassEntry> = mutableListOf()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            BaseConstant.ITEM_CLASS_A -> AVH(
                ViewUtil.createView(activity, R.layout.base_adapter_class_manage_a), type
            )
            BaseConstant.ITEM_CLASS_A_EMPTY -> AEmptyVH(
                ViewUtil.createView(activity, R.layout.base_adapter_class_manage_a_empty), type
            )
            BaseConstant.ITEM_CLASS_B -> BVH(
                ViewUtil.createView(activity, R.layout.base_adapter_class_manage_b), type
            )
            else -> BEmptyVH(
                ViewUtil.createView(activity, R.layout.base_adapter_class_manage_b_empty), type
            )
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val entity = dataSource[position]
        when (getItemViewType(position)) {
            BaseConstant.ITEM_CLASS_A -> (holder as AVH).updateUI(activity, entity, listener)
            BaseConstant.ITEM_CLASS_A_EMPTY -> (holder as AEmptyVH).updateUI(
                activity,
                entity,
                listener
            )
            BaseConstant.ITEM_CLASS_B -> (holder as BVH).updateUI(activity, entity, listener)
            else -> (holder as BEmptyVH).updateUI(activity, entity, listener)
        }
    }

    override fun getItemCount(): Int {
        return dataSource.size
    }


    override fun getItemViewType(position: Int): Int {
        val entity = dataSource[position]
        val t1 = entity.T_1
        val t2 = entity.T_2
        val s1 = entity.S_1
        val s2 = entity.S_2

        return when (entity.class_classify) {
            "A" -> {
                when (t1 == null && t2 == null && s1?.isEmpty() ?: true && s2?.isEmpty() ?: true) {
                    true -> BaseConstant.ITEM_CLASS_A_EMPTY
                    else -> BaseConstant.ITEM_CLASS_A
                }
            }
            else -> {
                when (t1 == null && s1?.isEmpty() ?: true && s2?.isEmpty() ?: true) {
                    true -> BaseConstant.ITEM_CLASS_B_EMPTY
                    else -> BaseConstant.ITEM_CLASS_B
                }
            }
        }
    }
}


private abstract class BaseVH(itemView: View, type: String) : RecyclerView.ViewHolder(itemView) {

    private val rlTop: RoundRelativeLayout = itemView.findViewById(R.id.rlTop)
    private val tvTimeRange: TextView = itemView.findViewById(R.id.tvTimeRange)
    private val tvAge: TextView = itemView.findViewById(R.id.tvAge)
    private val tvClaName: TextView = itemView.findViewById(R.id.tvClaName)
    private val tvClaNo: TextView = itemView.findViewById(R.id.tvClaNo)
    private val tvStateName: TextView = itemView.findViewById(R.id.tvStateName)
    private val tvCourseName: TextView = itemView.findViewById(R.id.tvCourseName)
    private val ivEdit: ImageView = itemView.findViewById(R.id.ivEdit)


    fun updateUI(act: Activity, entity: ClassEntry, listener: OnClassPersonListener?) {
        entity.course_color.let {
            rlTop.delegate.backgroundColor = Color.parseColor(it)
        }

        tvTimeRange.text = entity.class_time
        tvAge.text = if (entity.stage_age.isEmpty()) {
            "0岁"
        } else {
            entity.stage_age.plus("岁")
        }
        tvClaNo.text = entity.ware_code
        tvClaName.text = entity.course_type_name
        tvCourseName.text = entity.course_type_name
        tvStateName.text = entity.stage_name
        ivEdit.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            if (!LocalCacheUtil.isTcRole()) {
                listener?.jumpPersonModify(entity)
            }
        }
        updatePersonUI(act, entity, listener)
    }

    abstract fun updatePersonUI(act: Activity, entity: ClassEntry, listener: OnClassPersonListener?)
}


private class AEmptyVH(itemView: View, type: String) : BaseVH(itemView, type) {

    private val tvStuFirst: TextView = itemView.findViewById(R.id.tvStuFirst)
    private val tvStuSecond: TextView = itemView.findViewById(R.id.tvStuSecond)
    private val tvTcFirst: TextView = itemView.findViewById(R.id.tvTcFirst)
    private val tvTcSecond: TextView = itemView.findViewById(R.id.tvTcSecond)

    override fun updatePersonUI(
        act: Activity,
        entity: ClassEntry,
        listener: OnClassPersonListener?
    ) {
        tvStuFirst.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            listener?.jumpStuAdd(entity, "1")
        }
        tvStuSecond.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            listener?.jumpStuAdd(entity, "2")
        }

        tvTcFirst.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            listener?.jumpTcAdd(entity, "1")
        }
        tvTcSecond.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            listener?.jumpTcAdd(entity, "2")
        }
    }
}

private class AVH(itemView: View, private val type: String) : BaseVH(itemView, type) {

    private val rvStu: RecyclerView = itemView.findViewById(R.id.rvStu)
    private val rvTc: RecyclerView = itemView.findViewById(R.id.rvTc)

    override fun updatePersonUI(
        act: Activity,
        entity: ClassEntry,
        listener: OnClassPersonListener?
    ) {
        // 学生
        val glm1 = object : GridLayoutManager(act, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rvStu.layoutManager = glm1
        rvStu.addItemDecoration(CommonGridItemDecoration(act, 3, 0, false))
        val stuAdapter = StuItemAdapter(act, type, entity, listener)
        rvStu.adapter = stuAdapter

        val stuList = mutableListOf<StudentEntry>()

        // 添加第一排学生
        stuList.addAll(entity.S_1 ?: mutableListOf())
        if (stuList.size < 3) {
            stuList.add(StudentEntry("1"))
        }
        for (i in 0 until (3 - stuList.size)) {
            stuList.add(StudentEntry())
        }

        // 添加第二排学生
        stuList.addAll(entity.S_2 ?: mutableListOf())
        if (stuList.size < 6) {
            stuList.add(StudentEntry("2"))
        }
        for (i in 0 until (6 - stuList.size)) {
            stuList.add(StudentEntry())
        }
        stuAdapter.refresh(stuList)


        // 教师
        val glm2 = object : GridLayoutManager(act, 1) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rvTc.layoutManager = glm2
        rvTc.addItemDecoration(CommonGridItemDecoration(act, 1, 0, false))
        val tcAdapter = TcItemAdapter(act, type, entity, listener)
        rvTc.adapter = tcAdapter

        val tcList = mutableListOf<TeacherEntry>()
        entity.T_1?.let {
            if (it.teacher_id?.isNotEmpty() == true) {
                tcList.add(it)
            } else {
                tcList.add(TeacherEntry("1"))
            }
        } ?: let {
            tcList.add(TeacherEntry("1"))
        }

        entity.T_2?.let {
            if (it.teacher_id?.isNotEmpty() == true) {
                tcList.add(it)
            } else {
                tcList.add(TeacherEntry("2"))
            }
        } ?: let {
            tcList.add(TeacherEntry("2"))
        }

        tcAdapter.refresh(tcList)
    }
}

private class BEmptyVH(itemView: View, type: String) : BaseVH(itemView, type) {

    private val tvStu: TextView = itemView.findViewById(R.id.tvStu)
    private val tvTc: TextView = itemView.findViewById(R.id.tvTc)

    override fun updatePersonUI(
        act: Activity,
        entity: ClassEntry,
        listener: OnClassPersonListener?
    ) {
        tvStu.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            if (!LocalCacheUtil.isTcRole()) {
                listener?.jumpStuAdd(entity, "1")
            }
        }

        tvTc.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            if (!LocalCacheUtil.isTcRole()) {
                listener?.jumpTcAdd(entity, "1")
            }
        }
    }

}

private class BVH(itemView: View, private val type: String) : BaseVH(itemView, type) {

    private val rvStu: RecyclerView = itemView.findViewById(R.id.rvStu)
    private val rvTc: RecyclerView = itemView.findViewById(R.id.rvTc)

    @SuppressLint("SetTextI18n")

    override fun updatePersonUI(
        act: Activity,
        entity: ClassEntry,
        listener: OnClassPersonListener?
    ) {

        // 学生
        val glm1 = object : GridLayoutManager(act, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rvStu.layoutManager = glm1
        rvStu.addItemDecoration(CommonGridItemDecoration(act, 3, 0, false))
        val stuAdapter = StuItemAdapter(act, type, entity, listener)
        rvStu.adapter = stuAdapter

        val stuList = mutableListOf<StudentEntry>()
        stuList.addAll(entity.S_1 ?: mutableListOf())
        stuList.addAll(entity.S_2 ?: mutableListOf())
        if (stuList.size < 6) {
            stuList.add(StudentEntry("1"))
        }
        for (i in 0..(6 - stuList.size)) {
            stuList.add(StudentEntry())
        }
        stuAdapter.refresh(stuList)

        // 教师
        val glm2 = object : GridLayoutManager(act, 1) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rvTc.layoutManager = glm2
        rvTc.addItemDecoration(CommonGridItemDecoration(act, 1, 0, false))
        val tcAdapter = TcItemAdapter(act, type, entity, listener)
        rvTc.adapter = tcAdapter

        val tcList = mutableListOf<TeacherEntry>()
        entity.T_1?.let {
            tcList.add(it)
        } ?: let {
            val emptyTc1 = TeacherEntry("1")
            tcList.add(emptyTc1)
        }
        tcAdapter.refresh(tcList)
    }
}

private class StuItemAdapter(
    val act: Activity,
    val type: String,
    val entity: ClassEntry,
    val listener: OnClassPersonListener?
) :
    BaseRecyclerAdapter<StudentEntry>(R.layout.base_layout_adapter_class_manage) {

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(vh: SmartViewHolder, p1: StudentEntry, p2: Int) {
        val tvAdd = vh.itemView.findViewById<TextView>(R.id.tvAdd)

        val personView = vh.itemView.findViewById<RelativeLayout>(R.id.personView)
        val ivPic = vh.itemView.findViewById<CircleImageView>(R.id.ivPic)
        val tvName = vh.itemView.findViewById<TextView>(R.id.tvName)
        val tvHour = vh.itemView.findViewById<TextView>(R.id.tvHour)
        if (p1.member_state_color?.isNotEmpty() == true) {
            tvName.setTextColor(Color.parseColor(p1.member_state_color))
        } else {
            tvName.setTextColor(ContextCompat.getColor(act, R.color.common_main_black))
        }
        when {
            EmptyUtil.isEmpty(p1.sortNo) -> {
                tvAdd.visibility = View.GONE
                personView.visibility = View.GONE
            }
            EmptyUtil.isEmpty(p1.member_id) -> {
                tvAdd.visibility = View.VISIBLE
                personView.visibility = View.GONE
                tvAdd.text = "添加\n学员"
                if (type == BaseConstant.TYPE_EVALUATE || !LocalCacheUtil.isCanEditClassRoom()) {
                    tvAdd.visibility = View.GONE
                }
            }
            else -> {
                tvAdd.visibility = View.GONE
                personView.visibility = View.VISIBLE
                GlideUtil.into(act, p1.member_head, ivPic, R.drawable.base_icon_person_add_default)
                if (p1.is_job_ok == "1") {
                    ivPic.borderWidth = 5
                    ivPic.borderColor = ContextCompat.getColor(vh.itemView.context, R.color.orange)
                } else {
                    ivPic.borderWidth = 0
                }
                tvName.text = p1.member_name
                tvHour.visibility = View.VISIBLE
                tvHour.text = p1.course_num.plus("课时")
            }
        }

        personView.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            listener?.jumpStuDetail(p1.member_id ?: "", p1.member_name ?: "", entity.course_list_id)
        }

        tvAdd.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            if (EmptyUtil.isEmpty(p1.sortNo)) return@setOnClickListener
            if (!LocalCacheUtil.isTcRole()) {
                listener?.jumpStuAdd(entity, p1.sortNo ?: "")
            }
        }
    }
}

private class TcItemAdapter(
    val act: Activity,
    val type: String,
    val entity: ClassEntry,
    val listener: OnClassPersonListener?
) :
    BaseRecyclerAdapter<TeacherEntry>(R.layout.base_layout_adapter_class_manage) {

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(vh: SmartViewHolder, p1: TeacherEntry, p2: Int) {

        val tvAdd = vh.itemView.findViewById<TextView>(R.id.tvAdd)

        val personView = vh.itemView.findViewById<RelativeLayout>(R.id.personView)
        val ivPic = vh.itemView.findViewById<CircleImageView>(R.id.ivPic)
        val tvName = vh.itemView.findViewById<TextView>(R.id.tvName)
        val tvBkState = vh.itemView.findViewById<RoundTextView>(R.id.tvBkState)

        var preId = ""
        var hasBk = false

        when {
            EmptyUtil.isEmpty(p1.teacher_id) -> {
                tvAdd.visibility = View.VISIBLE
                personView.visibility = View.GONE
                tvAdd.text = "添加\n教师"
                if (type == BaseConstant.TYPE_EVALUATE || !LocalCacheUtil.isCanEditClassRoom()) {
                    tvAdd.visibility = View.GONE
                }
            }
            else -> {
                tvAdd.visibility = View.GONE
                personView.visibility = View.VISIBLE
                GlideUtil.into(act, p1.teacher_head, ivPic, R.drawable.base_icon_person_add_default)
                tvName.text = p1.teacher_name
                tvBkState.visibility = View.VISIBLE

                val preStrArr = p1.taecher_prepare_id?.split(";") ?: listOf()
                if (preStrArr.isNotEmpty()) preId = preStrArr[0]
                if (preStrArr.size > 1) {
                    val preState = preStrArr[1]
                    hasBk = when (preState) {
                        "1" -> true
                        else -> false
                    }
                }

                when (hasBk) {
                    true -> {
                        tvBkState.text = "已备课"
                        tvBkState.delegate.backgroundColor =
                            ResUtil.getColor(act, R.color.common_main_black)
                    }
                    else -> {
                        tvBkState.text = "未备课"
                        tvBkState.delegate.backgroundColor =
                            ResUtil.getColor(act, R.color.base_color_99)
                    }
                }

            }

        }

        personView.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            listener?.dealBkLogic(
                entity.class_id ?: "",
                hasBk,
                preId
            )
        }

        tvAdd.setOnClickListener {
            if (ViewUtil.isFastDoubleClick()) return@setOnClickListener
            listener?.jumpTcAdd(entity, p1.sort_no ?: "1")
        }
    }

}


